package org.huel.backend.controller;

import org.huel.backend.domain.dto.AttendanceSearchDTO;
import org.huel.backend.domain.dto.AttendanceStatsDTO;
import org.huel.backend.domain.dto.StudentAttendanceDTO;
import org.huel.backend.domain.dto.StudentScoreDTO;
import org.huel.backend.domain.entity.Attendance;
import org.huel.backend.domain.entity.CourseAttendance;
import org.huel.backend.mapper.CourseAttendanceMapper;
import org.huel.backend.service.impl.AttendanceService;
import org.huel.backend.service.impl.StudentScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class AttendanceController {

    @Autowired
    private StudentScoreService studentScoreService;
    @Autowired
    private AttendanceService attendanceService;
    /**
     * 获取出勤统计摘要
     */
    @GetMapping("/attendance/summary")
    public ResponseEntity<Map<String, Object>> getAttendanceSummary() {
        System.out.println("Fetching attendance summary...");
        Map<String, Object> summary = studentScoreService.getAttendanceSummary();
        return ResponseEntity.ok(summary);
    }

    /**
     * 获取成绩最高的学生
     * @param limit 限制数量
     * @return 学生成绩列表
     */
    @GetMapping("/students/topscores")
    public ResponseEntity<List<StudentScoreDTO>> getTopStudentsByScore(
            @RequestParam(defaultValue = "5") int limit) {
        List<StudentScoreDTO> students = studentScoreService.getTopStudentsByScore(limit);
        return ResponseEntity.ok(students);
    }
    /**
     * 搜索出勤记录
     * @param requestData 请求数据
     * @return 响应结果
     */
    @PostMapping("/search")
    public Map<String, Object> searchAttendance(@RequestBody Map<String, Object> requestData) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 构建搜索条件
            AttendanceSearchDTO searchDTO = buildSearchDTO(requestData);

            Map<String, Object> searchResult = attendanceService.searchAttendance(searchDTO);
            result.put("success", true);
            result.put("data", searchResult);
            result.put("message", "搜索成功");
            result.put("timestamp", java.time.LocalDateTime.now().toString());
            result.put("user", "hoaixanghao");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "搜索失败: " + e.getMessage());
            result.put("timestamp", java.time.LocalDateTime.now().toString());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取所有班级ID
     * @param requestData 请求数据
     * @return 响应结果
     */
    @PostMapping("/classes")
    public Map<String, Object> getAllClassIds(@RequestBody(required = false) Map<String, Object> requestData) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<String> classIds = attendanceService.getAllClassIds();
            result.put("success", true);
            result.put("data", classIds);
            result.put("message", "获取成功");
            result.put("timestamp", java.time.LocalDateTime.now().toString());
            result.put("user", "hoaixanghao");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取失败: " + e.getMessage());
            result.put("timestamp", java.time.LocalDateTime.now().toString());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取所有课程名称
     * @param requestData 请求数据
     * @return 响应结果
     */
    @PostMapping("/courses")
    public Map<String, Object> getAllCourseNames(@RequestBody(required = false) Map<String, Object> requestData) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<String> courseNames = attendanceService.getAllCourseNames();
            result.put("success", true);
            result.put("data", courseNames);
            result.put("message", "获取成功");
            result.put("timestamp", java.time.LocalDateTime.now().toString());
            result.put("user", "hoaixanghao");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取失败: " + e.getMessage());
            result.put("timestamp", java.time.LocalDateTime.now().toString());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取所有学生姓名
     * @param requestData 请求数据
     * @return 响应结果
     */
    @PostMapping("/students")
    public Map<String, Object> getAllStudentNames(@RequestBody(required = false) Map<String, Object> requestData) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<String> studentNames = attendanceService.getAllStudentNames();
            result.put("success", true);
            result.put("data", studentNames);
            result.put("message", "获取成功");
            result.put("timestamp", java.time.LocalDateTime.now().toString());
            result.put("user", "hoaixanghao");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取失败: " + e.getMessage());
            result.put("timestamp", java.time.LocalDateTime.now().toString());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取学生出勤统计
     * @param requestData 请求数据
     * @return 响应结果
     */
    @PostMapping("/stats/students")
    public Map<String, Object> getStudentAttendanceStats(@RequestBody(required = false) Map<String, Object> requestData) {
        Map<String, Object> result = new HashMap<>();
        try {
            AttendanceSearchDTO searchDTO = buildSearchDTO(requestData != null ? requestData : new HashMap<>());

            List<AttendanceStatsDTO> stats = attendanceService.getStudentAttendanceStats(searchDTO);
            result.put("success", true);
            result.put("data", stats);
            result.put("message", "获取成功");
            result.put("timestamp", java.time.LocalDateTime.now().toString());
            result.put("user", "hoaixanghao");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取失败: " + e.getMessage());
            result.put("timestamp", java.time.LocalDateTime.now().toString());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取课程出勤统计
     * @param requestData 请求数据
     * @return 响应结果
     */
    @PostMapping("/stats/courses")
    public Map<String, Object> getCourseAttendanceStats(@RequestBody(required = false) Map<String, Object> requestData) {
        Map<String, Object> result = new HashMap<>();
        try {
            AttendanceSearchDTO searchDTO = buildSearchDTO(requestData != null ? requestData : new HashMap<>());

            List<AttendanceStatsDTO> stats = attendanceService.getCourseAttendanceStats(searchDTO);
            result.put("success", true);
            result.put("data", stats);
            result.put("message", "获取成功");
            result.put("timestamp", java.time.LocalDateTime.now().toString());
            result.put("user", "hoaixanghao");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取失败: " + e.getMessage());
            result.put("timestamp", java.time.LocalDateTime.now().toString());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取班级出勤统计
     * @param requestData 请求数据
     * @return 响应结果
     */
    @PostMapping("/stats/classes")
    public Map<String, Object> getClassAttendanceStats(@RequestBody(required = false) Map<String, Object> requestData) {
        Map<String, Object> result = new HashMap<>();
        try {
            AttendanceSearchDTO searchDTO = buildSearchDTO(requestData != null ? requestData : new HashMap<>());

            List<AttendanceStatsDTO> stats = attendanceService.getClassAttendanceStats(searchDTO);
            result.put("success", true);
            result.put("data", stats);
            result.put("message", "获取成功");
            result.put("timestamp", java.time.LocalDateTime.now().toString());
            result.put("user", "hoaixanghao");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取失败: " + e.getMessage());
            result.put("timestamp", java.time.LocalDateTime.now().toString());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取出勤统计摘要
     * @param requestData 请求数据
     * @return 响应结果
     */
    @PostMapping("/stats/summary")
    public Map<String, Object> getAttendanceSummary(@RequestBody(required = false) Map<String, Object> requestData) {
        Map<String, Object> result = new HashMap<>();
        try {
            AttendanceSearchDTO searchDTO = buildSearchDTO(requestData != null ? requestData : new HashMap<>());

            Map<String, Object> summary = attendanceService.getAttendanceSummary(searchDTO);
            result.put("success", true);
            result.put("data", summary);
            result.put("message", "获取成功");
            result.put("timestamp", java.time.LocalDateTime.now().toString());
            result.put("user", "hoaixanghao");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取失败: " + e.getMessage());
            result.put("timestamp", java.time.LocalDateTime.now().toString());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 构建搜索条件DTO
     * @param requestData 请求数据
     * @return 搜索条件DTO
     */
    private AttendanceSearchDTO buildSearchDTO(Map<String, Object> requestData) {
        AttendanceSearchDTO searchDTO = new AttendanceSearchDTO();

        if (requestData.get("classId") != null && !((String) requestData.get("classId")).isEmpty()) {
            searchDTO.setClassId((String) requestData.get("classId"));
        }
        if (requestData.get("studentName") != null && !((String) requestData.get("studentName")).isEmpty()) {
            searchDTO.setStudentName((String) requestData.get("studentName"));
        }
        if (requestData.get("courseName") != null && !((String) requestData.get("courseName")).isEmpty()) {
            searchDTO.setCourseName((String) requestData.get("courseName"));
        }
        if (requestData.get("studentId") != null && !((String) requestData.get("studentId")).isEmpty()) {
            searchDTO.setStudentId((String) requestData.get("studentId"));
        }
        if (requestData.get("isAbsent") != null) {
            searchDTO.setIsAbsent((Integer) requestData.get("isAbsent"));
        }
        if (requestData.get("startDate") != null && !((String) requestData.get("startDate")).isEmpty()) {
            searchDTO.setStartDate((String) requestData.get("startDate"));
        }
        if (requestData.get("endDate") != null && !((String) requestData.get("endDate")).isEmpty()) {
            searchDTO.setEndDate((String) requestData.get("endDate"));
        }
        if (requestData.get("page") != null) {
            searchDTO.setPage((Integer) requestData.get("page"));
        }
        if (requestData.get("pageSize") != null) {
            searchDTO.setPageSize((Integer) requestData.get("pageSize"));
        }
        if (requestData.get("sortBy") != null && !((String) requestData.get("sortBy")).isEmpty()) {
            searchDTO.setSortBy((String) requestData.get("sortBy"));
        }
        if (requestData.get("sortOrder") != null && !((String) requestData.get("sortOrder")).isEmpty()) {
            searchDTO.setSortOrder((String) requestData.get("sortOrder"));
        }

        return searchDTO;
    }
}
